var $ = getApp().globalData.eui;
$.page({
    data: {
        "catindex": 0,
        "cats": [],
        "products": [],
        "cond": {
            "pageindex": 1,
            "pagesize": 8,
            "catid": 0
        },
        "totalpage": 0
    },
    onLoad: function (options) {

        var me = this;

        $.api("mall.Cat.LoadAll", {}).then(function (value) {
            me.setData({
                "cats": value
            });
            if (value.length) {
                me.refresh();
            }
        });

    },
    onclick6: function (e) {

        var me = this;

        var index = $.toInt(e.currentTarget.dataset.index);
        me.setData({
            "catindex": index
        });

        $.api("mall.Product.ListPage", {
                pageindex: 1,
                pagesize: 10,
                catid: me.data.cats[me.data.catindex].id
            })
            .then(function (value) {
                me.setData({
                    "products": value.datas
                });
            });

    },
    onclick12: function (e) {

        var me = this;

        $.go("/pages/product/detail?id=" + e.currentTarget.dataset.id);

    },
    onScrollViewUpload9: function (e) {

        var me = this;

        me.loadNextPage();

    },
    onScrollViewDownRefresh9: function (e) {

        var me = this;

        me.refresh();

    },

    refresh: function () {

        var me = this;
        me.data.cond.pageindex = 0;
        me.loadNextPage();
    },

    loadNextPage: function () {

        var me = this;
        var cond = me.data.cond;
        if (me.data.cats.length) {
            cond.catid = me.data.cats[me.data.catindex].id;
            cond.pageindex++;
            if (cond.pageindex === 1) me.data.products = []; //第一页要重置

            $.api("mall.Product.ListPage", cond)
                .then(function (value) {
                    var p = me.data.products;
                    console.log("after product.ListPage:"+$.toJson(value));
                    $.each(value.datas,function (product) {
                       var icon = product.icon;
                       $.log("== icon:"+icon);
                       if( !(icon.indexOf("http:") == 0 || icon.indexOf("https:") == 0) ){
                           product.icon = $.getConfig("server_url")+"/"+$.getConfig("tenantid")+icon;
                       }
                    });
                    if ($.count(value.datas) > 0)
                        p = p.concat(value.datas);
                    me.setData({
                        "products": p,
                        "totalpage": value.totalpage
                    });

                }, function (reason) {
                    console.log(reason.message);
                })


        }

    }

});